home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Java Primer Plus
/
Java Primer Plus (Waite Group Proess)(1996).iso
/
chapter17
/
BinaryTree.java
< prev
next >
Wrap
Text File
|
1995-12-31
|
3KB
|
133 lines
/* Binary Tree Class */
import java.util.Stack;
class BinaryTree {
BinaryTreeEntry root = new BinaryTreeEntry();
/* empty constructor */
public BinaryTree() {}
/* method to add a node to the Binary tree */
public void addnode(int k,Object someobject) throws
DuplicateKeyException {
boolean leftright = true;
BinaryTreeEntry next,here=null;
/* Is someone sending null objects? */
if (someobject == null) throw new NullPointerException();
/* Check for Duplicates */
if (searchtree(k) != null)
throw new DuplicateKeyException("Key already exists in Structure");
System.out.println();
if (root.node == null) { root.node = someobject;
root.key = k;
return;
}
next = root;
while (next != null) {
here = next;
leftright = (k > here.key);
next = here.child[(leftright)?0:1];
}
next = here.child[(leftright)?0:1] = new BinaryTreeEntry();
next.parent = here;
next.key = k;
next.node = someobject;
}
/* public method frontend search */
public Object searchfor(int k) {
BinaryTreeEntry temp = searchtree(k);
if (temp == null) return null;
return temp.node;
}
/* private tree search */
private BinaryTreeEntry searchtree(int k) {
boolean leftright = true;
BinaryTreeEntry columbus = root;
while (columbus != null) {
if (columbus.key == k) return columbus;
leftright = (k > columbus.key);
columbus = columbus.child[(leftright)?0:1];
if (leftright) System.out.print("RIGHT ");
else System.out.print("LEFT ");
}
return null;
}
/* Deletes node with given key */
public void deleter(int k) {
int whichkid = 0;
BinaryTreeEntry temp;
BinaryTreeEntry exnode = searchtree(k);
if (exnode == null) return;
BinaryTreeEntry exparent = exnode.parent;
if (exparent != null)
whichkid = (exnode == exparent.child[0])?0:1;
/* Easy cases */
for (int g=0;g<2;++g) {
if (exnode.child[g] == null) {
if (exnode.child[1-g] != null)
exnode.child[1-g].parent = exparent;
if (exparent == null) root = exnode.child[1-g];
else
exparent.child[whichkid] = exnode.child[1-g];
return;
}
}
temp = exnode.child[1];
while (temp.child[0] != null)
temp = temp.child[0];
if (temp != exnode.child[1]) {
deleter(temp.key);
temp.child[1] = exnode.child[1];
}
temp.child[0] = exnode.child[0];
temp.parent = exparent;
if (exparent == null) root = temp;
else
exparent.child[whichkid] = temp;
}
/* methods to print out tree */
public void prtree() {
zip(root);
}
public void zip(BinaryTreeEntry x) {
if (x == null) return;
System.out.print(x.key + " --> " );
if (x.child[0] != null)
System.out.print(x.child[0].key + " " );
if (x.child[1] != null)
System.out.print(x.child[1].key);
System.out.println();
if (x.child[0] != null) zip(x.child[0]);
if (x.child[1] != null) zip(x.child[1]);
}
}